package oop.ex2.expression;

import java.util.ArrayList;
import oop.ex2.exceptions.UnrecognizedVariable;

/**
 * This node implements a custom function. A custom function is specified by a list of argument
 * names, an expression tree which it uses to evaluate an expression, and an expression solver
 * instance which it uses to the the values of the argument values.
 * 
 * In order to calculate it's values it parses it's input values just like regular function, and
 * then uses them to set the values of it's arguments. After that, it calls it's expression tree's
 * calculate function.
 * @author daniel_i_l
 *
 */
public class CustomFunctionNode extends FunctionNode {
    
	private static boolean BOUNDED_PARAMETERS = true;
    private ExpressionTree _functionCalcultor;
    private ArrayList<String> _argumentNames;
    private ExpressionSolver _expressionSolver;

    /**
     * Build a custom function node.
     * @param matchedString The string that was matched that caused this function to be created.
     * @param argumentNames The list of function arguments.
     * @param functionCalculator The expression tree used to evaluate the function.
     * @param expressionSolver The expression solver that's used to set variable values.
     */
	public CustomFunctionNode(String matchedString,
            ArrayList<String> argumentNames, ExpressionTree functionCalculator,
            ExpressionSolver expressionSolver) {
		super(matchedString, argumentNames.size(), BOUNDED_PARAMETERS);

        _functionCalcultor = functionCalculator;
        _argumentNames = argumentNames;
        _expressionSolver = expressionSolver;
	}

	@Override
	public double calculateNode() throws UnrecognizedVariable {
		//initialize arguments
        int i=0;
        for (String arg : _argumentNames)
        {
            _expressionSolver.setVarValue(arg, _children.get(i).calculateNode());
            i++;
        }

        return _functionCalcultor.calculateTree();
	}

}
